package com.ct.deadlockdetetor.service.impl;

import com.ct.deadlockdetetor.common.enums.ResultCode;
import com.ct.deadlockdetetor.common.exception.ServiceException;
import com.ct.deadlockdetetor.domain.resource.Resource;
import com.ct.deadlockdetetor.domain.resource.dto.ResourceAddDTO;
import com.ct.deadlockdetetor.domain.resource.dto.ResourceQueryDTO;
import com.ct.deadlockdetetor.domain.resource.vo.ResourceVO;
import com.ct.deadlockdetetor.mapper.ResourceMapper;
import com.ct.deadlockdetetor.service.ResourceService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    public boolean register(ResourceAddDTO resourceAddDTO) {
        checkResource(resourceAddDTO);
        Resource resource = new Resource();
        resource.setResourceId(resourceAddDTO.getResourceId());
        resource.setTotalInstances(resourceAddDTO.getTotalInstances());
        resource.setAvailableInstances(resourceAddDTO.getTotalInstances());
        resourceMapper.insert(resource);
        return true;
    }

    @Override
    public List<ResourceVO> list(ResourceQueryDTO resourceQueryDTO) {
        PageHelper.startPage(resourceQueryDTO.getPageNum(), resourceQueryDTO.getPageSize());
        return resourceMapper.selectResourceList(resourceQueryDTO);
    }

    @Override
    public boolean delete(Integer resourceId) {
        Resource resource = resourceMapper.selectById(resourceId);
        if (resource.getAvailableInstances() < resource.getTotalInstances()) {
            throw new ServiceException(ResultCode.RESOURCE_IS_USED);
        }

        resourceMapper.deleteById(resourceId);
        return true;
    }

    private void checkResource(ResourceAddDTO resourceAddDTO) {
        if (null == resourceAddDTO) {
            throw new ServiceException(ResultCode.RESOURCE_INFO_IS_EMPTY);
        }
    }
}
